package com.intretech.umsin.openoffice;

import com.intretech.umsin.openoffice.properties.OpenOfficeProperties;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * @version V1.0
 * @ClassName: OpenOfficeStartUp
 * @Description: OpenOfficeStartUp 服务实现
 * @author: 李启联
 * @date: 2022-5-12 14:46
 * @Copyright: Copyright (c) 2022
 */
@Slf4j
public class OpenOfficeStartUp {


    private OpenOfficeProperties properties;

    private Process p;

    public OpenOfficeStartUp(OpenOfficeProperties properties) {
        this.properties = properties;
    }

    @PostConstruct
    public void start() {
        if (properties.getPath() == null) {
            log.error("您想要启动服务,但path属性未配置无法启动,且type值为start");
            return;
        }
        if (properties.getType() != StartType.START) {
            log.error("如您想要启动服务,请设置type属性值为start");
            return;
        }

        String command = properties.getPath() + " -headless -accept=\"socket,host=" + properties.getIp() + ",port=8100;urp;\" -nofirststartwizard ";
        try {
            p = Runtime.getRuntime().exec(command);
            log.debug("OpenOffice启动状态:" + p.isAlive());
        } catch (IOException e) {
            e.printStackTrace();
            // 关闭进程
            if (p != null) {
                p.destroy();
            }
        }

    }

    @PreDestroy
    public void destory() {
        if (p.isAlive()) {
            p.destroy();
            log.debug("关闭OpenOffice服务进程");
        }
    }
}
